package com.mwumz.third.common;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.mwumz.third.error.GeneralError;
import com.mwumz.third.error.IError;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * @Author: wumz
 * @Date: 2020/7/2 14:36
 * @Version 1.0
 */
@JsonSerialize(
        using = ResponseSerializer.class
)
@ApiModel(
        description = "Rest Api返回统一数据结构体"
)
public class Response<T> {
    private static final long serialVersionUID = -6602365878131231511L;
    public static final String CODE_SUCCESS = "000000";
    public static final String MSG_SUCCESS = "SUCCESS";

    @ApiModelProperty(
            value = "业务码：000000表示操作成功，其他返回请参考业务码列表",
            name = "code",
            dataType = "String"
    )
    private String code = "000000";
    @ApiModelProperty(
            value = "返回消息",
            name = "msg",
            dataType = "String"
    )

    private String description = "SUCCESS";
    private T data;

    public Response() {
    }

    public Response(T data) {
        this.data = data;
    }

    public static <T> Response<T> success(T data) {
        return result(data, "000000", "SUCCESS");
    }

    public static Response success() {
        return success((Object)null);
    }

    public static <T> Response<PageResult<T>> pageSuccess(PageList<T> pageList) {
        return success(PageResult.of(pageList));
    }

    public static Response error() {
        return error(GeneralError.SYSTEM_INTERNAL_ERROR);
    }

    public static Response error(IError error, String extMessage) {
        Response response = new Response((Object)null);
        response.code = error.getNamespace() + error.getErrorCode();
        if (extMessage != null) {
            response.description = String.format("%s, %s", error.getErrorMessage(), extMessage);
        } else {
            response.description = error.getErrorMessage();
        }

        return response;
    }

    public static <T> Response<T> result(T data, String code, String msg) {
        Response<T> response = new Response();
        response.setCode(code);
        response.setData(data);
        response.setDescription(msg);
        return response;
    }

    public static Response error(IError error) {
        Response response = new Response((Object)null);
        response.code = error.getNamespace() + error.getErrorCode();
        response.description = error.getErrorMessage();
        return response;
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
